package com.example.autoplaywebview;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private WebView webView;

    private static final int MAX_RETRIES = 3;
    private int retryCount = 0;
    private Handler handler = new Handler();
    private static final long RETRY_DELAY = 3000; // 3秒后重试

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
        return false;
    }

    private void loadWebPage() {
        if (isNetworkAvailable()) {
//            webView.loadUrl("http://8.138.165.177/lab-mall/statistics/overview");
            webView.loadUrl("http://192.168.40.58:5100/lab-mall/statistics/overview");
        } else {
//            handleError("网络连接不可用");
            if (retryCount < MAX_RETRIES) {
                retryCount++;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadWebPage();
                    }
                }, RETRY_DELAY);
                Toast.makeText(this, "网络连接不可用，" + RETRY_DELAY / 1000 + "秒后重试（" + retryCount + "/" + MAX_RETRIES + "）",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置窗口背景色为白色
        getWindow().setBackgroundDrawableResource(android.R.color.black);

        // 隐藏状态栏和导航栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_FULLSCREEN);

        // 创建WebView
        webView = new WebView(this);
        setContentView(webView);

        // 配置WebView设置
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true); // 启用JavaScript
        webSettings.setMediaPlaybackRequiresUserGesture(true); // 允许自动播放
        webSettings.setDomStorageEnabled(true); // 启用DOM存储
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // 允许混合内容
        webSettings.setAllowFileAccess(true); // 允许文件访问
        webSettings.setUseWideViewPort(true); // 使用宽视图
        webSettings.setLoadWithOverviewMode(true); // 自适应屏幕
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不使用缓存
        webSettings.setBuiltInZoomControls(true); // 启用内置缩放控件
        webSettings.setDisplayZoomControls(false); // 隐藏缩放控件
        webSettings.setDefaultTextEncodingName("UTF-8"); // 设置默认编码
//        webSettings.setAppCacheEnabled(true); // 禁用应用缓存
        webSettings.setLoadsImagesAutomatically(true); // 自动加载图片

        // 设置WebView背景为白色
        webView.setBackgroundColor(android.graphics.Color.WHITE);

        // 设置WebViewClient
        webView.setWebViewClient(new WebViewClient() {
            private static final int PAGE_LOAD_TIMEOUT = 20000; // 20秒超时
            private Runnable timeoutRunnable;
            private static final String TAG = "WebView";

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.i(TAG, "开始加载页面: " + url);

                // 设置加载超时
                timeoutRunnable = new Runnable() {
                    @Override
                    public void run() {
                        if (webView != null) {
                            webView.stopLoading();
//                            handleError("页面加载超时");
                        }
                    }
                };
                view.postDelayed(timeoutRunnable, PAGE_LOAD_TIMEOUT);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.i(TAG, "页面加载完成: " + url);
                // 移除超时回调
                if (timeoutRunnable != null) {
                    view.removeCallbacks(timeoutRunnable);
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                String errorMessage = "页面加载失败";
                String url = request.getUrl().toString();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    errorMessage += ": " + error.getDescription();
                    Log.e(TAG, String.format("加载错误 - URL: %s, 错误码: %d, 描述: %s",
                            url, error.getErrorCode(), error.getDescription()));
                } else {
                    Log.e(TAG, String.format("加载错误 - URL: %s", url));
                }
//                handleError(errorMessage);
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request,
                    WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                String url = request.getUrl().toString();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    Log.e(TAG, String.format("HTTP错误 - URL: %s, 状态码: %d, 原因: %s",
                            url, errorResponse.getStatusCode(), errorResponse.getReasonPhrase()));
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                Log.d(TAG, "正在加载资源: " + url);
            }

//            private void handleError(String errorMessage) {
//                if (webView != null) {
//                    // 显示错误信息
//                    String errorHtml = "<html><body style='display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background-color:white;'><div style='text-align:center;color:#666;'><h2>"
//                            + errorMessage + "</h2><p>请检查网络连接后重试</p></div></body></html>";
//                    webView.loadData(errorHtml, "text/html", "UTF-8");
//                    Log.e(TAG, errorMessage);
//
//                    // 自动重试加载
//                    if (retryCount < MAX_RETRIES) {
//                        retryCount++;
//                        handler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (webView != null) {
//                                    loadWebPage();
//                                    Toast.makeText(MainActivity.this, "正在重试加载（" + retryCount + "/" + MAX_RETRIES + "）",
//                                            Toast.LENGTH_SHORT).show();
//                                }
//                            }
//                        }, RETRY_DELAY);
//                    } else {
//                        Toast.makeText(MainActivity.this, "加载失败，请检查网络连接后重试", Toast.LENGTH_LONG).show();
//                        retryCount = 0; // 重置重试计数
//                    }
//                }
//            }
        });

        // 设置WebChromeClient
        webView.setWebChromeClient(new WebChromeClient());

        // 加载网页
        loadWebPage();
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }
}